<?php

namespace app\common\model\cms;

use app\common\model\BaseModel;
use helper\Files;
use helper\Tree;
use think\facade\Env;

class ClassModel extends BaseModel
{

  protected $table = 'cms_class';

  /**
   * 获取树型数据
   * @param bool $refresh
   * @return array
   * @throws \Exception
   */
  public function getList($refresh = false)
  {
    if (cache("?cms_class") && $refresh == false) return cache('cms_class');
    $list     = $this->order("show_order asc")->select()->toArray();
    $tree = $this->formatTree($list,'name');
    cache('cms_class', $tree);
    return $tree;
  }

  public function getTree(){
    if (cache("?cms_class")) {
      $list = cache('cms_class');
    }else{
      $list = $this->getList(true);
    }
    $tree = Tree::channelLevel($list,0);
    return $tree;
  }

  /**
   * 获取指定模型对应分类
   * @param $tableName
   * @return array
   * @throws \Exception
   */
  public function getClass($tableName)
  {
    $arr  = $this->getList();
    $list = [];
    foreach ($arr as $k => $v) {
      if ($v['table_name'] == $tableName) {
        $list[] = $v;
      }
    }
    return $list;
  }

  /**
   * 获取指定栏目
   * @param $id
   * @return mixed
   * @throws \Exception
   */
  public function getInfo($id)
  {
    $list = $this->getList();
    return $list[$id];
  }

  /**
   * 添加分类
   * @param $data
   * @return ClassModel|\think\Model
   * @throws \Exception
   */
  public function add($data)
  {
    $data['is_show'] = isset($data['is_show']) ? 1 : 0;
    $info            = self::create($data);
    $this->getList(true);
    return $info;
  }

  /**
   * 编辑分类
   * @param $data
   * @return ClassModel|\think\Model
   * @throws \Exception
   */
  public function edit($data)
  {
    $data['is_show'] = isset($data['is_show']) ? 1 : 0;
    $info            = self::update($data);
    $this->getList(true);
    return $info;
  }

  /**
   * 删除分类
   * @param $id
   * @throws \Exception
   */
  public function del($id)
  {
    $tableName = $this->where('id', $id)->value('table_name');
    if ($this->where('pid', $id)->find()) abort(500, '存在下级分类');
    if (DetailModel::suffix($tableName)->where('class_id', $id)->find()) abort(500, '存在对应内容');
    $this->where('id', $id)->delete();
  }

  /**
   * 获取模板文件名
   * @param $key
   * @return array
   */
  public function getTplList($type=null){
    $arr=[];
    $path = root_path().'view/home/pc/cms';
    $dir = Files::getDir($path,['html']);
    foreach($dir as $k=>$v){
      if(!empty($type)){
        if(strstr($v['filename'],$type)!==false) $arr[]=['id'=>$v['filename'],'name'=>$v['filename']];
      }else{
        $arr[]=['id'=>$v['filename'],'name'=>$v['filename']];
      }
    }
    if(empty($arr)) $arr[]=['id'=>$type.'default','name'=>$type.'default'];
    return $arr;
  }

}